package com.up.vms.interfaces.rest.intercepters;

import com.alibaba.fastjson.JSONObject;
//import com.up.vms.application.authenticate.MerchantTokenManager;
//import com.up.vms.dto.merchant.MerchantUserDTO;
import com.up.vms.infrastructure.annotations.MerchantAuthManager;
import com.up.vms.infrastructure.constants.EmpAPIConstants;
import com.up.vms.infrastructure.util.CommonUtils;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.security.auth.message.AuthException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 运营/商户的身份鉴权拦截器
 * Created by wangshd on 2019/4/3.
 */

@Component
@NoArgsConstructor
@Slf4j
public class MerchantAuthenticationInterceptor extends HandlerInterceptorAdapter {

//    @Autowired
//    MerchantTokenManager tokenManager;

    //鉴权失败后返回的错误信息，默认为401 unauthorized
    private String unauthorizedErrorMessage = "401 unauthorized";

    //鉴权失败后返回的HTTP错误码，默认为401
    private int merchantUnauthorizedErrorCode = HttpServletResponse.SC_UNAUTHORIZED;

    private final static String LABEL_MERCHANT_USER_ID = "merchantUserId";

    private final static String LABEL_MERCHANT_ID = "merchantId";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MerchantAuthManager annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(MerchantAuthManager.class);
        } else {
            return true;
        }

        if (annotation == null) {
            return true;
        }
        return this.initMerchantSession(request, response);
    }


    private boolean initMerchantSession(HttpServletRequest req, HttpServletResponse resp) throws AuthException{

        //获取用户凭证
        String authToken = req.getHeader(EmpAPIConstants.MERCHANT_TOKEN);
        log.info("token is {}", authToken);

        //token凭证为空
        if (CommonUtils.isNull(authToken)) {
            JSONObject jsonObject = new JSONObject();

            PrintWriter out = null;
            try {
                resp.setStatus(merchantUnauthorizedErrorCode);
                resp.setContentType(MediaType.APPLICATION_JSON_VALUE);

                jsonObject.put("code", (resp).getStatus());
                jsonObject.put("message", HttpStatus.UNAUTHORIZED);
                out = resp.getWriter();
                out.println(jsonObject);
                return false;
            } catch (Exception e) {
                e.printStackTrace();
                log.error("商户鉴权失败: {}", e.getMessage());
            } finally {
                if (null != out) {
                    out.flush();
                    out.close();
                }
            }
        }

        log.info("MerchantAuthenticationInterceptor：current token is {}", authToken);
//        MerchantUserDTO merchantUser = tokenManager.getUserInfoByToken(authToken);
//        log.info("MerchantAuthenticationInterceptor：current merchantUser is {}", JSONObject.toJSONString(merchantUser));
//        if (CommonUtils.isNotNull(merchantUser)) {
//            req.setAttribute(LABEL_MERCHANT_USER_ID, merchantUser.getUserId());
//            req.setAttribute(LABEL_MERCHANT_ID, merchantUser.getMerchant().getMerchantId());
//            tokenManager.refreshUserToken(authToken);
//        } else {
//            throw new AuthException(unauthorizedErrorMessage);
//        }
        return true;
    }
}
